package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        //延时双删  解决数据一致性
        /**
         * 从 product 对象的 productSkuList 中提取出每个 ProductSku 对象的 id 属性，并将这些 id 存储在一个 List<Long> 类型的列表中
         * 1.创建 List<Long> 变量：List<Long> skuIdList;
         * 2.获取 productSkuList 并转换为流：product.getProductSkuList().stream()
         * 3.映射操作：.map(ProductSku::getId)
         *            使用 map 方法将 Stream 中的每个 ProductSku 对象映射为其 id 属性的值。
         *            这里使用了方法引用 ProductSku::getId，表示对于 Stream 中的每个 ProductSku 对象，调用其 getId() 方法。
         * 4.收集操作：.collect(Collectors.toList());
         *            使用 collect 方法将映射后的 Stream 中的元素收集到一个新的 List 中。Collectors.toList() 是一个收集器，它将流中的元素存储到一个 List 中。
         */
        List<Long> skuIdList = product.getProductSkuList().stream().map(ProductSku::getId).collect(Collectors.toList());
        skuIdList.forEach(skuId -> {
            String dataKey = "product:sku:" + skuId;
            this.redisTemplate.delete(dataKey);
        });
        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);


        //睡觉一段时间
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //删除缓存
        skuIdList.forEach(skuId -> {
            String dataKey = "product:sku:" + skuId;
            this.redisTemplate.delete(dataKey);
        });

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if (status == 1) {
            product.setStatus(1);
            productMapper.updateById(product);

            ProductSku productSku = new ProductSku();
            productSku.setStatus(1);
            //根据ID修改Status状态
            LambdaUpdateWrapper<ProductSku> productSkuLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            productSkuLambdaUpdateWrapper.eq(ProductSku::getProductId, id);
            productSkuMapper.update(productSku, productSkuLambdaUpdateWrapper);
            String key = "sku:product:data";
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), true);
            });
        } else {
            product.setStatus(-1);
            productMapper.updateById(product);

            ProductSku productSku = new ProductSku();
            productSku.setStatus(-1);

            productSkuMapper.update(productSku, new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId, id));
            String key = "sku:product:data";
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), false);
            });

        }

    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            //1从缓存中获取数据
            //1.1 构建业务数据key形式：前缀+唯一标识
            String dataKey = "product:sku:" + skuId;
            //1.2 查询redis中的数据
            ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);//强转成我们需要的类型
            //1.3查到数据直接返回结果数据
            if (redisTemplate.hasKey(dataKey)) {
                log.info("命中缓存，直接返回，线程ID:{}，线程名称:{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                return productSku;
            }
            //2获得分布式锁
            //2.1 尝试构建锁
            String lockKey = "product:sku:lock" + skuId;
            //2.2UUID 作为线程标识
            String lockValue = UUID.randomUUID().toString().replaceAll("-", "");//将UUID中的-替换成空字符串
            //2.3 利用redis的set nx(唯一性) ex(过期时间) 获得分布式锁
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
            if (flag) {
                //3成功获得锁后执行业务将查询业务存到redis缓存中
                log.info("获得锁成功，线程ID:{}，线程名称:{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                try {
                    productSku = this.getProductSkuFromDB(skuId);
                    long ttl = productSku == null ? (new Random().nextInt(10) + 60) : (new Random().nextInt(10) + 600);
                    redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);
                    return productSku;
                } finally {
                    //4.业务执行完毕后释放锁
                    String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "    return redis.call(\"del\",KEYS[1])\n" +
                            "else\n" +
                            "    return 0\n" +
                            "end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(scriptText);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript, Arrays.asList(lockKey), lockValue);
                }
            } else {
                //5.获取锁失败，进行自旋
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.info("获取锁失败，进行自旋:线程ID:{}，线程名称:{}", Thread.currentThread().getId(), Thread.currentThread().getName());
                return this.getProductSku(skuId);
            }
        } catch (RuntimeException e) {
            //6.兜底处理，中途发生异常，业务数据直接从数据库中获取
            log.error("[商品服务]查询商品信息异常：{}", e);
            return this.getProductSkuFromDB(skuId);
        }
    }

    private ProductSku getProductSkuFromDB(Long skuId) {
        return getSkuFromDB(skuId);
    }

    private ProductSku getSkuFromDB(Long skuId) {
        return productSkuMapper.selectById(skuId);
    }


    @Override
    public Product getProduct(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)

    /**
     * 查询mysql中的productSku中的切在购物车里面的商品数据get实时价格
     *
     * @param skuIdList
     * @return
     */
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            throw new ServiceException("查询集合为空");
        }
        List<ProductSku> skuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList));
        if (CollectionUtils.isEmpty(skuList)) {
            throw new ServiceException("数据不存在");
        }
        return skuList.stream().map(productSku -> {//Map映射  取一点映射一点数据
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(productSku.getId()); //从 productSku 中 得到id set到 skuPrice 的skuId
            skuPrice.setSalePrice(productSku.getSalePrice());
            skuPrice.setMarketPrice(productSku.getMarketPrice());
            return skuPrice;
        }).toList();
    }

    @Transactional //要么全锁 要么全不锁
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        //分布式锁 去重 共享标记
        String key = "sku:checkAndLock:" + orderNo;//上锁，让别人看见这个库存我已经锁了，你就不能再操作了
        //需要锁定的库存信息保存到redis中  便于后续业务  下单失败解锁库存，
        String dataKey = "sku:lock:data:" + orderNo;//  保存订单信息 便于后面业务使用
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);//同一个订单号 其他的无影响
        if (!ifAbsent){
            if (redisTemplate.hasKey(dataKey)){
                return "";
            } else {
                return "请勿重复提交";
            }
        }
        //检查库存
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock skuStock = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum()); //查询操作
            if (skuStock == null) { //库存不够
                skuLockVo.setIsHaveStock(false);
            } else {
                skuLockVo.setIsHaveStock(true);
            }
        }
        //判断库存是否够用
        if (skuLockVoList.stream().anyMatch((skuLockVo -> !skuLockVo.getIsHaveStock()))) {//有任意一个库存不够的商品
            List<SkuLockVo> noHaveSkuLockVoList = skuLockVoList.stream().filter((skuLockVo -> !skuLockVo.getIsHaveStock())).toList();
            //拼接xxxx商品库存不够  返回即可
            StringBuilder stringBuilder = new StringBuilder();
            for (SkuLockVo skuLockVo : noHaveSkuLockVoList) {
                stringBuilder.append(skuLockVo.getSkuId()+"--商品库存不够了");
            }
            redisTemplate.delete(key);//删除分布式锁
            return  stringBuilder.toString();

        } else { //商品库存均够 则锁定库存
            for (SkuLockVo skuLockVo : skuLockVoList) {
                int row = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());//修改库存数量
                if (row == 0) {
                    redisTemplate.delete(key);//删除分布式锁
                    throw new ServiceException("锁定库存失败");
                }
            }
        }

        redisTemplate.opsForValue().set(dataKey,skuLockVoList);//不要设置失效时间  其他业务需要这个数据 使用完会对其进行删除的
        return "";//空串表示成功
    }

    @Transactional
    @Override
    public void unlock(String orderNo) {
        String key = "sku:unlock:" + orderNo;//上锁，让别人看见这个库存我已经要进行释放操作了，你就不能再操作了
        String dataKey = "sku:lock:data:" + orderNo;
        //去重
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!ifAbsent){
            log.info("解锁库存   重复提交  去重处理");
            return;
        }
        //找缓存数据
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)) {
            throw new ServiceException("解锁库存失败，缓存数据为空");
        }
        //解锁
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());//解锁操作
            if(row == 0) {
                redisTemplate.delete(key);
                throw new ServiceException("解锁库存失败啊");
            }
        }
        //删除缓存数据 已经解锁库存了  与减库存二选一 防止再次解锁库存
        redisTemplate.delete(dataKey);
    }

    @Transactional
    @Override
    public void minus(String orderNo) {
        String key = "sku:minus:" + orderNo;//上锁，让别人看见这个库存我已经要进行释放操作了，你就不能再操作了
        String dataKey = "sku:lock:data:" + orderNo;
        //去重
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!ifAbsent){
            log.info("减库存   重复提交  去重处理");
            return;
        }
        //找缓存数据
        List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVoList)) {
            throw new ServiceException("解锁库存失败，缓存数据为空");
        }
        //减
        for (SkuLockVo skuLockVo : skuLockVoList) {
            int row = skuStockMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());//减库操作
            if(row == 0) {
                redisTemplate.delete(key);
                throw new ServiceException("减库存失败啊");
            }
        }
        //删除缓存数据 已经减库存了  与减库存二选一 防止再次减库存
        redisTemplate.delete(dataKey);
    }
}